#!/usr/bin/env julia

"""
Test script to verify Julia module precompilation and runtime initialization.

This script tests that:
1. The TongLun module can be precompiled without errors
2. Runtime initialization works correctly
3. Basic functionality works after initialization
"""

using Pkg

println("Testing TongLun.jl precompilation and runtime initialization...")
println("=" ^ 60)

# Test 1: Module precompilation
println("1. Testing module precompilation...")
try
    # Force precompilation by removing existing precompiled files
    Pkg.precompile()
    println("   ✅ Module precompiles successfully")
catch e
    println("   ❌ Precompilation failed: $e")
    exit(1)
end

# Test 2: Module loading without TONGLUN_CORELIB_PATH (should not fail at precompile)
println("\n2. Testing module loading before runtime setup...")
try
    # Temporarily unset the environment variable
    old_path = get(ENV, "TONGLUN_CORELIB_PATH", nothing)
    if old_path !== nothing
        delete!(ENV, "TONGLUN_CORELIB_PATH")
    end
    
    # This should work fine (module loads but C API not initialized)
    @eval using TongLun
    println("   ✅ Module loads successfully without TONGLUN_CORELIB_PATH")
    
    # Restore environment variable
    if old_path !== nothing
        ENV["TONGLUN_CORELIB_PATH"] = old_path
    end
catch e
    println("   ❌ Module loading failed: $e")
    exit(1)
end

# Test 3: Runtime initialization
println("\n3. Testing runtime initialization...")
try
    # Check if environment variable is set
    corelib_path = get(ENV, "TONGLUN_CORELIB_PATH", nothing)
    if corelib_path === nothing
        println("   ⚠️  TONGLUN_CORELIB_PATH not set - skipping runtime tests")
        println("   Set TONGLUN_CORELIB_PATH to test runtime initialization")
    else
        println("   TONGLUN_CORELIB_PATH = $corelib_path")
        
        # Force re-initialization by manually calling __init__
        if isfile(corelib_path)
            println("   Library file exists, testing initialization...")
            
            # This should trigger __init__ and load the C API
            TongLun.__init__()
            println("   ✅ Runtime initialization successful")
            
            # Test basic functionality
            println("\n4. Testing basic functionality...")
            try
                # Test exporting a simple function
                TongLun.export_fn("test.simple_add", (a, b) -> a + b)
                
                # Test calling the exported function
                result = TongLun.call_fn("test.simple_add", 2, 3)
                if result == 5
                    println("   ✅ Basic function export/call works: 2 + 3 = $result")
                else
                    println("   ❌ Unexpected result: expected 5, got $result")
                end
                
            catch e
                println("   ❌ Basic functionality test failed: $e")
            end
            
        else
            println("   ⚠️  Library file not found at $corelib_path")
            println("   Build the Rust library first to test runtime functionality")
        end
    end
    
catch e
    println("   ❌ Runtime initialization failed: $e")
    println("   This is expected if the C library is not built yet")
end

println("\n" * "=" * 60)
println("Precompilation test completed!")
println("\nSummary:")
println("- Module precompilation: ✅ (works without C library)")
println("- Module loading: ✅ (works without environment variable)")  
println("- Runtime initialization: depends on TONGLUN_CORELIB_PATH and built library")

println("\nTo fully test runtime functionality:")
println("1. Build the Rust library: cargo build --release")
println("2. Set TONGLUN_CORELIB_PATH=/path/to/libtonglun_core.so")
println("3. Run this test again") 